package smartclass.present;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import smartclass.data.TableItem;
import smartclass.fragment.TeacherFolderFragment;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.smartclass.R;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.pen.Spen;
import com.samsung.android.sdk.pen.SpenSettingEraserInfo;
import com.samsung.android.sdk.pen.SpenSettingPenInfo;
import com.samsung.android.sdk.pen.SpenSettingSelectionInfo;
import com.samsung.android.sdk.pen.SpenSettingTextInfo;
import com.samsung.android.sdk.pen.document.SpenInvalidPasswordException;
import com.samsung.android.sdk.pen.document.SpenNoteDoc;
import com.samsung.android.sdk.pen.document.SpenObjectBase;
import com.samsung.android.sdk.pen.document.SpenObjectContainer;
import com.samsung.android.sdk.pen.document.SpenObjectImage;
import com.samsung.android.sdk.pen.document.SpenObjectTextBox;
import com.samsung.android.sdk.pen.document.SpenPageDoc;
import com.samsung.android.sdk.pen.document.SpenPageDoc.HistoryListener;
import com.samsung.android.sdk.pen.document.SpenPageDoc.HistoryUpdateInfo;
import com.samsung.android.sdk.pen.document.SpenUnsupportedTypeException;
import com.samsung.android.sdk.pen.document.SpenUnsupportedVersionException;
import com.samsung.android.sdk.pen.engine.SpenColorPickerListener;
import com.samsung.android.sdk.pen.engine.SpenContextMenuItemInfo;
import com.samsung.android.sdk.pen.engine.SpenControlBase;
import com.samsung.android.sdk.pen.engine.SpenControlList;
import com.samsung.android.sdk.pen.engine.SpenControlListener;
import com.samsung.android.sdk.pen.engine.SpenFlickListener;
import com.samsung.android.sdk.pen.engine.SpenPageEffectListener;
import com.samsung.android.sdk.pen.engine.SpenPenChangeListener;
import com.samsung.android.sdk.pen.engine.SpenReplayListener;
import com.samsung.android.sdk.pen.engine.SpenSelectionChangeListener;
import com.samsung.android.sdk.pen.engine.SpenSurfaceView;
import com.samsung.android.sdk.pen.engine.SpenTouchListener;
import com.samsung.android.sdk.pen.recognition.SpenRecognitionBase.ResultListener;
import com.samsung.android.sdk.pen.recognition.SpenRecognitionInfo;
import com.samsung.android.sdk.pen.recognition.SpenShapeRecognition;
import com.samsung.android.sdk.pen.recognition.SpenShapeRecognitionManager;
import com.samsung.android.sdk.pen.settingui.SpenSettingEraserLayout;
import com.samsung.android.sdk.pen.settingui.SpenSettingEraserLayout.EventListener;
import com.samsung.android.sdk.pen.settingui.SpenSettingPenLayout;
import com.samsung.android.sdk.pen.settingui.SpenSettingSelectionLayout;
import com.samsung.android.sdk.pen.settingui.SpenSettingTextLayout;

public class TeacherActivity extends FragmentActivity {

	private final int MODE_PEN = 0;
	private final int MODE_IMG_OBJ = 1;
	private final int MODE_TEXT_OBJ = 2;
	private final int MODE_ERASER = 3;
	private final int MODE_SELECT = 4;

	private final int CONTEXT_MENU_DELETE_ID = 100;
	private final int CONTEXT_MENU_GROUP_ID = 101;
	private final int CONTEXT_MENU_UNGROUP_ID = 102;
	private FrameLayout frameLayout;
	private RelativeLayout layoutContainer;
	private SpenSurfaceView mSpenSurfaceView;
	private SpenSettingPenLayout mPenSettingView;
	private SpenSettingEraserLayout mEraserSettingView;
	private SpenSettingTextLayout mTextSettingView;
	private SpenSettingSelectionLayout mSelectionSettingView;

	private Rect rect;
	
	private static ArrayList<Bitmap> arrayBitmap;
	private TextView   tvNumberPageShow;
	private ImageView penBtn;
	private ImageView eraserBtn;
	private ImageView textBtn;
	private ImageView undoBtn;
	private ImageView redoBtn;
	private ImageView changeBackground;
	private ImageView replayBtn;
	private ImageView captureBtn;
	private ImageView selectBtn;
	private ImageView shapeRecognitionBtn;

	private File mFilePath;
	private Context mContext;
	private ScaleGestureDetector onScale;

	private SpenNoteDoc mSpenNoteDoc;
	private SpenPageDoc mSpenPageDoc;

	private SpenShapeRecognition mShapeRecongnition;

	private int mMode = MODE_PEN;
	private int mToolType = SpenSurfaceView.TOOL_SPEN;
	private static final int REQUEST_CODE_SELECT_IMAGE_BACKGROUND = 8;
	private static final int SHOW_PAGE = 9;
	boolean isFeatureSpen = false;

	public static ActionBar actionBar;
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.teacher_activity);
		mContext = TeacherActivity.this;
		actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
		layout.setBackgroundColor(Color.GRAY);
		arrayBitmap = new ArrayList<Bitmap>();
		 
		tvNumberPageShow = (TextView) findViewById(R.id.tvNumberPage);
		 
		penBtn = (ImageView) findViewById(R.id.btnPen);
		eraserBtn = (ImageView) findViewById(R.id.btnEraser);
		textBtn = (ImageView) findViewById(R.id.btnText);
		undoBtn = (ImageView) findViewById(R.id.btnUndo);
		redoBtn = (ImageView) findViewById(R.id.btnRedo);
		changeBackground = (ImageView) findViewById(R.id.btnbackground);
		replayBtn = (ImageView) findViewById(R.id.btnreplay);
		captureBtn = (ImageView) findViewById(R.id.btncapture);
		selectBtn = (ImageView) findViewById(R.id.btnselect);
		shapeRecognitionBtn = (ImageView) findViewById(R.id.btnShapeRecognition);

		// -------------------------------------------Check
		// device----------------------------------//
		// -----------------------------------------------------------------------------------------//
		String filePath = TableItem.FILE_PATH;
		mFilePath = new File(filePath);
		Spen spen = new Spen();
		 try {
		 spen.initialize(mContext);
		 isFeatureSpen = spen.isFeatureEnabled(Spen.DEVICE_PEN);
		 } catch (SsdkUnsupportedException e) {
		 // TODO Auto-generated catch block
		 e.printStackTrace();
		 int type = e.getType();
		 switch (type) {
		 case SsdkUnsupportedException.VENDOR_NOT_SUPPORTED:
		 Toast.makeText(mContext, "This device is not Sam Sung Device",
		 Toast.LENGTH_LONG).show();
		 break;
		 case SsdkUnsupportedException.DEVICE_NOT_SUPPORTED:
		 Toast.makeText(mContext,
		 "This device is not supported Spen SDK",
		 Toast.LENGTH_LONG).show();
		 break;
		 case SsdkUnsupportedException.LIBRARY_NOT_INSTALLED:
		 Toast.makeText(mContext,
		 "The SDK Spen Library is not installed",
		 Toast.LENGTH_LONG).show();
		 break;
		 case SsdkUnsupportedException.LIBRARY_UPDATE_IS_REQUIRED:
		 Toast.makeText(mContext, "The SPen Library update is required",
		 Toast.LENGTH_LONG).show();
		 break;
		 case SsdkUnsupportedException.LIBRARY_UPDATE_IS_RECOMMENDED:
		 Toast.makeText(mContext,
		 "The SPen Library update is recommended",
		 Toast.LENGTH_LONG).show();
		 break;
		
		 default:
		 break;
		 }
		 finish();
		 }

		// --------------------------------------Set up
		// Layout------------------------------//
		frameLayout = (FrameLayout) findViewById(R.id.frameLayout);

		layoutContainer = (RelativeLayout) findViewById(R.id.layout_container);

		// ----------------------Set up Pen Setting View----------//
		mPenSettingView = new SpenSettingPenLayout(mContext, new String(),
				layoutContainer);
		if (mPenSettingView == null) {
			Toast.makeText(mContext, "Can not creat new PenSettingView",
					Toast.LENGTH_LONG).show();
			finish();
		}
		frameLayout.addView(mPenSettingView);

		// --------------------Set up Eraser Setting View-----------//
		mEraserSettingView = new SpenSettingEraserLayout(mContext,
				new String(), layoutContainer);
		if (mEraserSettingView == null) {
			Toast.makeText(mContext, "Cannot creat new EraserSettingView",
					Toast.LENGTH_LONG).show();
			finish();
		}
		frameLayout.addView(mEraserSettingView);

		// ------------------Set up Text Setting View-----------------//
		mTextSettingView = new SpenSettingTextLayout(mContext, new String(),
				new HashMap<String, String>(), layoutContainer);
		if (mTextSettingView == null) {
			Toast.makeText(mContext, "Cannot creat new TextSettingView",
					Toast.LENGTH_LONG).show();
			finish();
		}
		frameLayout.addView(mTextSettingView);
		frameLayout.setBackgroundResource(R.drawable.imagenote);

		// ------------------Set up Selection Setting View-----------//
		mSelectionSettingView = new SpenSettingSelectionLayout(mContext,
				new String(), layoutContainer);
		if (mSelectionSettingView == null) {
			Toast.makeText(mContext, "Cannot creat new SelectionSettingView",
					Toast.LENGTH_LONG).show();
			finish();
		}
		frameLayout.addView(mSelectionSettingView);

		// ---------------Creat SpenSurfaceView--------------------//
		mSpenSurfaceView = new SpenSurfaceView(mContext);
		if (mSpenSurfaceView == null) {
			Toast.makeText(mContext, "Cannot creat SurfaceView",
					Toast.LENGTH_LONG).show();
			finish();
		}
		layoutContainer.addView(mSpenSurfaceView);

		// ------------Set Canvas Setting View--------------------//
		mPenSettingView.setCanvasView(mSpenSurfaceView);
		mEraserSettingView.setCanvasView(mSpenSurfaceView);
		mTextSettingView.setCanvasView(mSpenSurfaceView);
		mSelectionSettingView.setCanvasView(mSpenSurfaceView);

		// ----------Set Up Note and Page Doc---------------------//
		Display display = getWindowManager().getDefaultDisplay();
		rect = new Rect();
		display.getRectSize(rect);
		try {
			mSpenNoteDoc = new SpenNoteDoc(mContext, rect.width(),
					rect.height());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Toast.makeText(mContext, "Can not creat new NoteDoc",
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
			finish();
		}
		mSpenPageDoc = mSpenNoteDoc.appendPage();
		mSpenPageDoc.clearHistory();
		mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);

		// ------------init Setting Info------------------------------//
		initPenSettingInfo();
		initEraseSettingInfo();
		initTextSettingInfo();
		showNumberPageCurrent();

		// -----------Set up Layout Listener--------------------------------//
		mSpenSurfaceView.setColorPickerListener(mColorPickerListener);
		mSpenSurfaceView.setPenChangeListener(mPenChangeListener);
		mSpenSurfaceView.setFlickListener(mFickListener);
		mEraserSettingView.setEraserListener(mEraserListener);
		mSpenPageDoc.setHistoryListener(mHistoryListener);
		mSpenSurfaceView.setReplayListener(mReplayListener);
		mSpenSurfaceView.setSelectionChangeListener(mSelectionListener);
		mSpenSurfaceView.setControlListener(mControlListener);
		mSpenSurfaceView.setZoomable(false);

		mSpenSurfaceView.setTouchListener(mPenTouchListener);


		// ------------Listener Button------------------------------//
		shapeRecognitionBtn.setOnClickListener(mShapeRecogn);
		selectBtn.setOnClickListener(mSelectBtnClickListener);
		penBtn.setOnClickListener(mPenBtnClickListener);
		penBtn.setOnLongClickListener(mOnLongPenClickListener);
		eraserBtn.setOnClickListener(mEraserBtnClickListener);
		eraserBtn.setOnLongClickListener(mOnLongEraserClickListener);
		textBtn.setOnClickListener(mTextClickListener);
		replayBtn.setOnClickListener(mPlayBtnClickListener);
		undoBtn.setOnClickListener(undoNredoBtnClickListener);
		undoBtn.setEnabled(mSpenPageDoc.isUndoable());
		redoBtn.setOnClickListener(undoNredoBtnClickListener);
		redoBtn.setEnabled(mSpenPageDoc.isRedoable());
		changeBackground.setOnClickListener(changeImageListener);
		captureBtn.setOnClickListener(mCaptureBtnClickListener);
		onScale = new ScaleGestureDetector(mContext, onScaleListener);
		selectButton(penBtn);

	}

	// -----------Build init Setting View---------------------------//
	private void initPenSettingInfo() {
		SpenSettingPenInfo penInfo = new SpenSettingPenInfo();
		penInfo.color = Color.GREEN;
		penInfo.size = 12;
		mSpenSurfaceView.setPenSettingInfo(penInfo);
		mPenSettingView.setInfo(penInfo);
		setTextInfo(penInfo, "Pen");

	}

	private void initEraseSettingInfo() {
		SpenSettingEraserInfo eraserInfo = new SpenSettingEraserInfo();
		eraserInfo.size = 30;
		mSpenSurfaceView.setEraserSettingInfo(eraserInfo);
		mEraserSettingView.setInfo(eraserInfo);
	}

	private void initTextSettingInfo() {
		int mCanvasWidth = 1080;
		SpenSettingTextInfo textInfo = new SpenSettingTextInfo();
		textInfo.size = Math.round(8.5 * mCanvasWidth / 360);
		mSpenSurfaceView.setTextSettingInfo(textInfo);
		mTextSettingView.setInfo(textInfo);
	}

	// --------Build Listener Button---------------------------------//s
	private SpenPenChangeListener mPenChangeListener = new SpenPenChangeListener() {

		@Override
		public void onChanged(SpenSettingPenInfo arg0) {
			// TODO Auto-generated method stub
			setTextInfo(arg0, null);
		}
	};
	private SpenColorPickerListener mColorPickerListener = new SpenColorPickerListener() {

		@Override
		public void onChanged(int arg0, int arg1, int arg2) {
			// TODO Auto-generated method stub
			if (mPenSettingView != null) {
				SpenSettingPenInfo penInfo = mPenSettingView.getInfo();
				penInfo.color = arg0;
				mPenSettingView.setInfo(penInfo);
			}
		}
	};

	private EventListener mEraserListener = new EventListener() {

		@Override
		public void onClearAll() {
			// TODO Auto-generated method stub
			mSpenPageDoc.removeAllObject();
			mSpenSurfaceView.update();
		}

	};

	private SpenSelectionChangeListener mSelectionListener = new SpenSelectionChangeListener() {

		@Override
		public void onChanged(SpenSettingSelectionInfo arg0) {
			mSelectionSettingView.setVisibility(View.GONE);
		}
	};

	private SpenControlListener mControlListener = new SpenControlListener() {

		@Override
		public void onRotationChanged(float arg0, SpenObjectBase arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onRectChanged(RectF arg0, SpenObjectBase arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onObjectChanged(ArrayList<SpenObjectBase> arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public boolean onMenuSelected(ArrayList<SpenObjectBase> objectList,
				int itemID) {
			// TODO Auto-generated method stub
			switch (itemID) {
			case CONTEXT_MENU_DELETE_ID:
				for (SpenObjectBase obj : objectList) {
					mSpenPageDoc.removeObject(obj);
				}
				mSpenSurfaceView.closeControl();
				mSpenSurfaceView.update();
				break;
			case CONTEXT_MENU_GROUP_ID:
				SpenObjectContainer objContainer = mSpenPageDoc.groupObject(
						objectList, false);
				mSpenSurfaceView.closeControl();
				mSpenPageDoc.selectObject(objContainer);
				mSpenSurfaceView.update();
				break;
			case CONTEXT_MENU_UNGROUP_ID:
				ArrayList<SpenObjectBase> objList = new ArrayList<SpenObjectBase>();
				for (SpenObjectBase selectedObj : objectList) {
					if (selectedObj.getType() == SpenObjectBase.TYPE_CONTAINER) {
						objContainer = (SpenObjectContainer) selectedObj;
						for (SpenObjectBase obj : objContainer.getObjectList()) {
							objList.add(obj);
						}

						mSpenPageDoc.ungroupObject(
								(SpenObjectContainer) selectedObj, false);
					}
				}
				mSpenSurfaceView.closeControl();
				mSpenPageDoc.selectObject(objList);
				mSpenSurfaceView.update();
				break;

			default:
				break;
			}
			return false;
		}

		@Override
		public boolean onCreated(ArrayList<SpenObjectBase> objectList,
				ArrayList<Rect> relativeRectList,
				ArrayList<SpenContextMenuItemInfo> menu,
				ArrayList<Integer> styleList, int pressType, PointF point) {
			menu.add(new SpenContextMenuItemInfo(CONTEXT_MENU_DELETE_ID,
					"Delete", true));
			if (objectList.size() > 1) {
				menu.add(new SpenContextMenuItemInfo(CONTEXT_MENU_GROUP_ID,
						"Group", true));
			}
			for (SpenObjectBase obj : objectList) {
				if (obj.getType() == SpenObjectBase.TYPE_CONTAINER) {
					menu.add(new SpenContextMenuItemInfo(
							CONTEXT_MENU_UNGROUP_ID, "UnGroup", true));
					break;
				}
			}

			if (objectList.size() == 1)
				return true;

			// Attach an individual control for each object.
			SpenControlList controlList = new SpenControlList(mContext,
					mSpenPageDoc);
			controlList.setObject(objectList);
			controlList.setGroup(false);
			mSpenSurfaceView.setControl(controlList);
			controlList.setContextMenu(menu);
			return false;
		}

		@Override
		public boolean onClosed(ArrayList<SpenObjectBase> arg0) {
			// TODO Auto-generated method stub
			return false;
		}
	};

	private final OnClickListener mShapeRecogn = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			
			SpenShapeRecognitionManager srm = new SpenShapeRecognitionManager(
					mContext);
			List<SpenRecognitionInfo> infoList = srm.getInfoList(
					SpenObjectBase.TYPE_STROKE, SpenObjectBase.TYPE_CONTAINER);
			final ArrayList<SpenObjectBase> oList = mSpenPageDoc
					.getObjectList(SpenPageDoc.FIND_TYPE_STROKE);
			try {
				mShapeRecongnition = srm.createRecognition(infoList.get(0));
				Log.e("test", "in shape button "+infoList.size() );
				mShapeRecongnition.setResultListener(new ResultListener() {
					
					@Override
					public void onResult(List<SpenObjectBase> arg0, List<SpenObjectBase> arg1) {
						// TODO Auto-generated method stub
						Log.e("test", "on result");
						mSpenPageDoc.removeObject(oList.get(oList.size()-1));
						mSpenPageDoc.appendObject(arg1.get(arg1.size()-1));
						
                        mSpenSurfaceView.update();
					}
				} );
				
				mShapeRecongnition.request(oList);
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("test", e.getMessage().toString());
			}

		}
	};

	private final View.OnClickListener mSelectBtnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			mSpenSurfaceView.closeControl();

			if (mSpenSurfaceView.getToolTypeAction(mToolType) == SpenSurfaceView.ACTION_SELECTION) {
				if (mSelectionSettingView.isShown())
					mSelectionSettingView.setVisibility(SpenSurfaceView.GONE);
				else {
					mSelectionSettingView
							.setViewMode(SpenSettingSelectionLayout.VIEW_MODE_NORMAL);
					mSelectionSettingView
							.setVisibility(SpenSurfaceView.VISIBLE);
				}
			} else {
				mMode = MODE_SELECT;
				selectButton(selectBtn);
				mSpenSurfaceView.setToolTypeAction(mToolType,
						SpenSurfaceView.ACTION_SELECTION);
			}
		}
	};
	private final View.OnClickListener mPenBtnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			setTextInfo(mSpenSurfaceView.getPenSettingInfo(), "Pen");
			if (mSpenSurfaceView.getToolTypeAction(mToolType) == SpenSurfaceView.ACTION_STROKE) {
				if (mPenSettingView.isShown()) {
					mPenSettingView.setVisibility(View.GONE);

				} else {
					mPenSettingView
							.setViewMode(SpenSettingPenLayout.VIEW_MODE_NORMAL);
					mPenSettingView.setVisibility(View.VISIBLE);

				}
			} else {
				selectButton(penBtn);
				mMode = MODE_PEN;
				// spenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_FINGER,
				// SpenSurfaceView.ACTION_NONE);
				mSpenSurfaceView.setToolTypeAction(mToolType,
						SpenSurfaceView.ACTION_STROKE);

			}
		}
	};

	private final OnLongClickListener mOnLongPenClickListener = new OnLongClickListener() {

		@Override
		public boolean onLongClick(View arg0) {
			// TODO Auto-generated method stub
			setTextInfo(mSpenSurfaceView.getPenSettingInfo(), "Pen");
			if (mPenSettingView.isShown()) {
				mPenSettingView.setVisibility(View.GONE);

			} else {
				mPenSettingView
						.setViewMode(SpenSettingPenLayout.VIEW_MODE_EXTENSION);
				mPenSettingView.setVisibility(View.VISIBLE);

			}
			return false;
		}
	};

	private final View.OnClickListener mEraserBtnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			setTextInfo(mSpenSurfaceView.getPenSettingInfo(), "Eraser");
			if (mSpenSurfaceView.getToolTypeAction(SpenSurfaceView.TOOL_SPEN) == SpenSurfaceView.ACTION_ERASER) {
				if (mEraserSettingView.isShown()) {
					mEraserSettingView.setVisibility(View.GONE);
				} else {
					mEraserSettingView
							.setViewMode(SpenSettingEraserLayout.VIEW_MODE_NORMAL);
					mEraserSettingView.setVisibility(View.VISIBLE);
				}
			} else {
				selectButton(eraserBtn);
				mMode = MODE_ERASER;
				// spenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_SPEN,
				// SpenSurfaceView.ACTION_NONE);
				mSpenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_SPEN,
						SpenSurfaceView.ACTION_ERASER);
			}
		}
	};

	private final OnLongClickListener mOnLongEraserClickListener = new OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {
			// TODO Auto-generated method stub
			setTextInfo(mSpenSurfaceView.getPenSettingInfo(), "Eraser");
			if (mEraserSettingView.isShown()) {
				mEraserSettingView.setVisibility(View.GONE);
			} else {
				mEraserSettingView
						.setViewMode(SpenSettingEraserLayout.VIEW_MODE_NORMAL);
				mEraserSettingView.setVisibility(View.VISIBLE);
			}
			return false;
		}
	};

	private final OnClickListener mTextClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mSpenSurfaceView.closeControl();

			if (mSpenSurfaceView.getToolTypeAction(mToolType) == SpenSurfaceView.ACTION_TEXT) {
				if (mTextSettingView.isShown()) {
					mTextSettingView.setVisibility(View.GONE);
				} else {
					mTextSettingView
							.setViewMode(SpenSettingTextLayout.VIEW_MODE_COLOR);
					mTextSettingView.setVisibility(View.VISIBLE);
				}
			} else {
				mMode = MODE_TEXT_OBJ;
				selectButton(textBtn);
				mSpenSurfaceView.setToolTypeAction(mToolType,
						SpenSurfaceView.ACTION_TEXT);
			}
		}
	};
	private final View.OnClickListener undoNredoBtnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Log.e("test", "Press Button");
			Toast.makeText(mContext, "press button", Toast.LENGTH_LONG).show();
			if (mSpenPageDoc == null) {
				return;
			}
			if (v.equals(undoBtn)) {
				if (mSpenPageDoc.isUndoable()) {
					HistoryUpdateInfo[] userData = mSpenPageDoc.undo();
					mSpenSurfaceView.updateUndo(userData);
				}
			} else if (v.equals(redoBtn)) {
				if (mSpenPageDoc.isRedoable()) {
					HistoryUpdateInfo[] userData = mSpenPageDoc.redo();
					mSpenSurfaceView.updateRedo(userData);
				}
			}

		}
	};

	private HistoryListener mHistoryListener = new HistoryListener() {

		@Override
		public void onCommit(SpenPageDoc arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onRedoable(SpenPageDoc arg0, boolean arg1) {
			// TODO Auto-generated method stub
			redoBtn.setEnabled(arg1);

		}

		@Override
		public void onUndoable(SpenPageDoc arg0, boolean arg1) {
			// TODO Auto-generated method stub

			undoBtn.setEnabled(arg1);

		}

	};

	private final OnClickListener changeImageListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			closeSettingView();
			callGalleryForInputImage(REQUEST_CODE_SELECT_IMAGE_BACKGROUND);
		}
	};

	private final OnClickListener mPlayBtnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			closeSettingView();
			setBtnEnabled(true);
			mSpenSurfaceView.startReplay();

		}
	};

	private SpenReplayListener mReplayListener = new SpenReplayListener() {

		@Override
		public void onProgressChanged(int arg0, int arg1) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onCompleted() {

			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					setBtnEnabled(true);
					undoBtn.setEnabled(mSpenPageDoc.isUndoable());
					redoBtn.setEnabled(mSpenPageDoc.isRedoable());
				}
			});
		}
	};

	private final OnClickListener mCaptureBtnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			closeSettingView();
			String filePath = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/SPen/images";
			File fileCacheItem = new File(filePath);
			if (!fileCacheItem.exists()) {
				Toast.makeText(mContext, "Save Path Creation Error",
						Toast.LENGTH_LONG).show();
				return;
			}
			filePath = fileCacheItem.getPath() + "/CaptureImg.png";
			captureSpenSurfaceView(filePath);

		}

	};

	private final SpenFlickListener mFickListener = new SpenFlickListener() {

		@Override
		public boolean onFlick(int arg0) {
			// TODO Auto-generated method stub
			int pageIndex = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
			int pageCount = mSpenNoteDoc.getPageCount();
			if (arg0 == DIRECTION_LEFT) {
				mSpenPageDoc = mSpenNoteDoc.getPage((pageIndex + pageCount - 1)
						% pageCount);
				mSpenSurfaceView.setPageDoc(mSpenPageDoc,
						SpenSurfaceView.PAGE_TRANSITION_EFFECT_LEFT,
						SpenSurfaceView.PAGE_TRANSITION_EFFECT_TYPE_SHADOW, 0);

			} else if (arg0 == DIRECTION_RIGHT) {
				if (mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId()) == pageCount - 1) {
					mSpenSurfaceView.closeControl();
					closeSettingView();

					mSpenPageDoc = mSpenNoteDoc.insertPage(mSpenNoteDoc
							.getPageIndexById(mSpenPageDoc.getId()) + 1);
					mSpenPageDoc
							.setBackgroundColor(Color.parseColor("#FFFFFF"));
					mSpenPageDoc.clearHistory();
					mSpenSurfaceView.setPageDoc(mSpenPageDoc,
							SpenSurfaceView.PAGE_TRANSITION_EFFECT_RIGHT,
							SpenSurfaceView.PAGE_TRANSITION_EFFECT_TYPE_SHADOW,
							0);
					mSpenSurfaceView
							.setPageEffectListener(new SpenPageEffectListener() {

								@Override
								public void onFinish() {
									// TODO Auto-generated method stub
									// Toast.makeText(mContext,
									// "Tao page thanh cong!",
									// Toast.LENGTH_LONG).show();
								}
							});
				} else {
					mSpenPageDoc = mSpenNoteDoc.getPage((pageIndex + 1)
							% pageCount);
					mSpenSurfaceView.setPageDoc(mSpenPageDoc,
							SpenSurfaceView.PAGE_TRANSITION_EFFECT_RIGHT,
							SpenSurfaceView.PAGE_TRANSITION_EFFECT_TYPE_SHADOW,
							0);
				}

			}
			showNumberPageCurrent();
			return false;
		}
	};
	private final SpenTouchListener mPenTouchListener = new SpenTouchListener() {

		@Override
		public boolean onTouch(View view, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_UP
					&& event.getToolType(0) == mToolType) {
				// Check if the control is created.
				SpenControlBase control = mSpenSurfaceView.getControl();
				if (control == null) {
					// When Pen touches the display while it is in Add
					// ObjectImage mode
					if (mMode == MODE_IMG_OBJ) {
						// Set a bitmap file to ObjectImage.
						SpenObjectImage imgObj = new SpenObjectImage();
						Bitmap imageBitmap = BitmapFactory
								.decodeResource(mContext.getResources(),
										R.drawable.ic_launcher);
						imgObj.setImage(imageBitmap);

						// Set the location to insert ObjectImage and add it to
						// PageDoc.
						float imgWidth = imageBitmap.getWidth();
						float imgHeight = imageBitmap.getHeight();
						RectF rect = getRealPoint(event.getX(), event.getY(),
								imgWidth, imgHeight);
						imgObj.setRect(rect, true);
						mSpenPageDoc.appendObject(imgObj);
						mSpenSurfaceView.update();

						imageBitmap.recycle();
						return true;
						// When Pen touches the display while it is in Add
						// ObjectTextBox mode
					} else if (mSpenSurfaceView.getToolTypeAction(mToolType) == SpenSurfaceView.ACTION_TEXT) {
						// Set the location to insert ObjectTextBox and add it
						// to PageDoc.
						SpenObjectTextBox textObj = new SpenObjectTextBox();
						RectF rect = getRealPoint(event.getX(), event.getY(),
								0, 0);
						rect.right += 350;
						rect.bottom += 50;
						textObj.setRect(rect, true);
						mSpenPageDoc.appendObject(textObj);
						mSpenPageDoc.selectObject(textObj);
						mSpenSurfaceView.update();
					}
				}
			}
			return onScale.onTouchEvent(event);
		}
	};

	private RectF getRealPoint(float x, float y, float width, float height) {
		float panX = mSpenSurfaceView.getPan().x;
		float panY = mSpenSurfaceView.getPan().y;
		float zoom = mSpenSurfaceView.getZoomRatio();
		width *= zoom;
		height *= zoom;
		RectF realRect = new RectF();
		realRect.set((x - width / 2) / zoom + panX, (y - height / 2) / zoom
				+ panY, (x + width / 2) / zoom + panX, (y + height / 2) / zoom
				+ panY);
		return realRect;
	}

	private SimpleOnScaleGestureListener onScaleListener = new SimpleOnScaleGestureListener() {

		float startScale;
		float endScale;

		@Override
		public boolean onScale(ScaleGestureDetector detector) {
			// TODO Auto-generated method stub
			return super.onScale(detector);
		}

		@Override
		public boolean onScaleBegin(ScaleGestureDetector detector) {
			// TODO Auto-generated method stub
			startScale = detector.getScaleFactor();
			return super.onScaleBegin(detector);
		}

		@Override
		public void onScaleEnd(ScaleGestureDetector detector) {
			// TODO Auto-generated method stub
			endScale = detector.getScaleFactor();

			if (startScale > endScale) {
				arrayBitmap.clear();
				Thread savingThread = new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (mSpenNoteDoc != null
								&& mSpenNoteDoc.getPageCount() > 0
								&& mSpenPageDoc != null) {
							for (int i = 0; i < mSpenNoteDoc.getPageCount(); i++) {
								mSpenPageDoc = mSpenNoteDoc.getPage(i);
								mSpenSurfaceView
										.setPageDoc(mSpenPageDoc, false);
								Bitmap imgBitmap = mSpenSurfaceView
										.capturePage((float) 0.4);
								arrayBitmap.add(imgBitmap);
							}
						}
						Intent intent = new Intent(mContext,
								ShowMultiScreen.class);

						startActivityForResult(intent, SHOW_PAGE);

					}
				});
				savingThread.run();
				super.onScaleEnd(detector);
			}

		}

	};

	// ---------------------------Set up Utils-----------------//
	public static ArrayList<Bitmap> addBitmap(Bitmap bitmap) {
		if (bitmap != null) {
			arrayBitmap.add(bitmap);
		}
		return arrayBitmap;
	}

	private void selectButton(View v) {
		penBtn.setSelected(false);
		penBtn.setBackgroundColor(Color.GRAY);
		eraserBtn.setSelected(false);
		eraserBtn.setBackgroundColor(Color.GRAY);
		textBtn.setSelected(false);
		textBtn.setBackgroundColor(Color.GRAY);
		selectBtn.setSelected(false);
		selectBtn.setBackgroundColor(Color.GRAY);
		v.setSelected(true);
		v.setBackgroundColor(Color.GREEN);
		closeSettingView();
	}

	private void closeSettingView() {
		mEraserSettingView.setVisibility(SpenSurfaceView.GONE);
		mPenSettingView.setVisibility(SpenSurfaceView.GONE);
		mTextSettingView.setVisibility(SpenSurfaceView.GONE);
		mSelectionSettingView.setVisibility(SpenSurfaceView.GONE);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		if (mPenSettingView != null) {
			mPenSettingView.close();
		}
		if (mEraserSettingView != null) {
			mEraserSettingView.close();
		}
		if (mSelectionSettingView != null) {
			mSelectionSettingView.close();
		}
		if (mSpenNoteDoc != null) {
			try {
				mSpenNoteDoc.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mSpenNoteDoc = null;
		}
		if (mSpenSurfaceView != null) {
			mSpenSurfaceView.close();
			mSpenSurfaceView = null;
		}
		if (mSpenPageDoc.isRecording()) {
			mSpenPageDoc.stopRecord();
		}

		try {
			if (mSpenSurfaceView.getReplayState() == SpenSurfaceView.REPLAY_STATE_PLAYING) {
				mSpenSurfaceView.stopReplay();
			}
		} catch (Exception e) {
			// TODO: handle exception
			// Log.e("Error", e.getMessage());
		}
	}

	private void callGalleryForInputImage(int requestCode) {

		try {
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
			startActivityForResult(intent, requestCode);
		} catch (ActivityNotFoundException e) {
			// TODO: handle exception
			Toast.makeText(mContext, "Activity Gallery not found!",
					Toast.LENGTH_LONG).show();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (data == null) {
				Toast.makeText(mContext, "Can not find iamge!",
						Toast.LENGTH_LONG).show();
				return;
			}
			if (requestCode == REQUEST_CODE_SELECT_IMAGE_BACKGROUND) {
				Uri image = data.getData();
				Cursor cursor = getContentResolver().query(
						Uri.parse(image.toString()), null, null, null, null);
				cursor.moveToNext();
				String imagePath = cursor.getString(cursor
						.getColumnIndex(MediaStore.MediaColumns.DATA));
				mSpenPageDoc.setBackgroundImage(imagePath);
				mSpenSurfaceView.update();
			}
			if (requestCode == SHOW_PAGE) {
				int index = data.getIntExtra("numberPageSelected", 1);
				mSpenPageDoc = mSpenNoteDoc.getPage(index);
				mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);
				showNumberPageCurrent();
				setTextInfo(mSpenSurfaceView.getPenSettingInfo(), null);
			}
		}
	}

	private void setBtnEnabled(boolean clickable) {
		penBtn.setEnabled(clickable);
		eraserBtn.setEnabled(clickable);
		undoBtn.setEnabled(clickable);
		redoBtn.setEnabled(clickable);
		changeBackground.setEnabled(clickable);
		replayBtn.setEnabled(clickable);
	}

	private void captureSpenSurfaceView(String filePath) {
		// TODO Auto-generated method stub
		Bitmap imgBitmap = mSpenSurfaceView.captureCurrentView(true);
		OutputStream out = null;
		try {
			out = new FileOutputStream(new File(filePath));
			imgBitmap.compress(CompressFormat.PNG, 100, out);
			Toast.makeText(
					mContext,
					"Captured images were stored in the file \'CaptureImg.png\'.",
					Toast.LENGTH_SHORT).show();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
						Uri.parse("file://"
								+ Environment.getExternalStorageDirectory())));
			} catch (IOException e) {

			}
		}
		imgBitmap.recycle();
	}

	private void setTextInfo(SpenSettingPenInfo arg0, String type) {
		if (type != null) {
//			tvType.setText(type);
		}
//		tvSizePen.setText(arg0.size + "    ");
//		String hexColor = String.format("#%06X", (0xFFFFFF & arg0.color));
//		tvColorPen.setText(hexColor + "  ");
	}

	private void showNumberPageCurrent() {
		int pageIndex = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId()) + 1;
		int pageCount = mSpenNoteDoc.getPageCount();
//		tvNumberPage.setText(pageIndex + "/ " + pageCount);
		tvNumberPageShow.setText("Page " + pageIndex);

	}

	private boolean saveNoteFile(final boolean isClose, final String type) {

		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

		final View layout = inflater.inflate(R.layout.save_dialog, null);
		TextView tvType = (TextView) layout.findViewById(R.id.tvType);
		final EditText edtnamefile = (EditText) layout
				.findViewById(R.id.edtName);
		AlertDialog.Builder saveAlert = new AlertDialog.Builder(mContext);
		saveAlert.setTitle("Save File| Enter file name");
		saveAlert.setView(layout);
		if (type.equals("spd")) {
			tvType.setText(".spd");
		} else if (type.equals("png")) {
			tvType.setText(".png");
		}
		saveAlert
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						File filePath = new File(Environment
								.getExternalStorageDirectory()
								.getAbsolutePath()
								+ "/SPen");
						if (!filePath.exists()) {
							if (!filePath.mkdirs()) {
								System.out.println("Cannot creat folder");
							}
						}
						String saveFilePath = filePath.getPath() + '/';
						String fileName = edtnamefile.getText().toString();
						if (!fileName.equals("")) {
							saveFilePath += fileName;
							if (type.equals("spd")) {
								saveFilePath += ".spd";
								saveNoteFile(saveFilePath);
								dialog.dismiss();
							} else if (type.equals("png")) {
								saveFilePath += ".png";
								captureSpenSurfaceView(saveFilePath);
							}
							if (isClose) {
								finish();
							}
						}
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								if (isClose) {
									finish();
								}
							}
						}).create().show();

		return true;
	}

	private boolean saveNoteFile(String filename) {
		try {
			mSpenNoteDoc.save(filename);
			Toast.makeText(mContext, "Save success", Toast.LENGTH_LONG).show();
		} catch (IOException ex) {
			Toast.makeText(mContext, "Cannot save", Toast.LENGTH_LONG).show();
		}
		return true;
	}

	private void loadNoteFile() {
		final String fileList[] = setFileList();
		if (fileList == null) {
			return;
		}

		new AlertDialog.Builder(mContext).setTitle("Select file")
				.setItems(fileList, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String strFilePath = mFilePath.getPath() + '/'
								+ fileList[which];

						try {
							// Create NoteDoc with the selected file.
							SpenNoteDoc tmpSpenNoteDoc = new SpenNoteDoc(
									mContext, strFilePath, rect.width(),
									SpenNoteDoc.MODE_WRITABLE);
							mSpenNoteDoc.close();
							mSpenNoteDoc = tmpSpenNoteDoc;
							if (mSpenNoteDoc.getPageCount() == 0) {
								mSpenPageDoc = mSpenNoteDoc.appendPage();
							} else {
								mSpenPageDoc = mSpenNoteDoc
										.getPage(mSpenNoteDoc
												.getLastEditedPageIndex());
							}
							mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);
							mSpenSurfaceView.update();
							Toast.makeText(mContext,
									"Successfully loaded noteFile.",
									Toast.LENGTH_SHORT).show();
						} catch (IOException e) {
							Toast.makeText(mContext, "Cannot open this file.",
									Toast.LENGTH_LONG).show();
						} catch (SpenUnsupportedTypeException e) {
							Toast.makeText(mContext,
									"This file is not supported.",
									Toast.LENGTH_LONG).show();
						} catch (SpenInvalidPasswordException e) {
							Toast.makeText(mContext,
									"This file is locked by a password.",
									Toast.LENGTH_LONG).show();
						} catch (SpenUnsupportedVersionException e) {
							Toast.makeText(
									mContext,
									"This file is the version that does not support.",
									Toast.LENGTH_LONG).show();
						} catch (Exception e) {
							Toast.makeText(mContext, "Failed to load noteDoc.",
									Toast.LENGTH_LONG).show();
						}
					}
				}).show();
	}

	private String[] setFileList() {
		String filePath = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/SPen/";
		File mFilePath = new File(filePath);
		if (!mFilePath.exists()) {
			if (!mFilePath.mkdir()) {
				Toast.makeText(mContext, "Save path creation Error",
						Toast.LENGTH_LONG).show();
				return null;
			}
		}
		File[] fileList = mFilePath.listFiles(new txtFileFilter());
		if (fileList == null) {
			Toast.makeText(mContext, "File does not exits", Toast.LENGTH_LONG)
					.show();
			return null;
		}
		int i = 0;
		String[] strFileList = new String[fileList.length];
		for (File file : fileList) {
			strFileList[i++] = file.getName();
		}

		return strFileList;
	}

	class txtFileFilter implements FilenameFilter {

		@Override
		public boolean accept(File arg0, String arg1) {
			// TODO Auto-generated method stub

			return (arg1.endsWith(".spd"));
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		switch (item.getItemId()) {
		case android.R.id.home:
			FragmentTransaction fragment = getSupportFragmentManager().beginTransaction();
			fragment.replace(R.id.layoutTeacher, new TeacherFolderFragment(this));
			fragment.addToBackStack(TeacherActivity.class.toString());
			fragment.commit();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
